<?php


namespace app\api\model;
use think\Db;

class Token
{
    protected $autoWriteTimestamp = true;
    protected $updateTime         = false;

    protected $expireTime = 7*60*60*24;
    /**
     * @param 生成token
     * @param
     * @return 加密后的字符串
     */
    public  function product_token($user_id,$act_type){
        $token_key = time().mt_rand('000000','999999')."codeforphp";
        //判断数据是否已存在
        $user_where['user_id'] = $user_id;
        $user_where['act_type'] =$act_type;
        $res = Db::name("user_token")->where($user_where)->find();

        if($res){
            if($res['expire_time'] > time()){
                $upda = array(
                    'last_time'=>time(),
                    'expire_time' => time() + $this->expireTime,

                );
                Db::name("user_token")->where($user_where)->update($upda);
                return $this->sys_token_encryption($res['token']);
            }
            //已存在更新
            $upda = array(
                'token'=>$token_key,
                'last_time'=>time(),
                'expire_time' => time() + $this->expireTime,

            );
            Db::name("user_token")->where($user_where)->update($upda);
        }else{
            //不存在新增
            $indata = array(
                'user_id'=>$user_id,
                'last_time'=>time(),
                'act_type'=> $act_type,
                'token'=>$token_key,
                'create_time' => time(),
                'expire_time' => time() + $this->expireTime,
            );
            Db::name("user_token")->insert($indata);
        }
        $token = $this->sys_token_encryption($token_key);
        return $token;
    }

    /**
     * @param 验证token
     * @param
     * @return 验证是否合法
     */
    public function check_token($user_id,$user_token,$act_type){

        $token_decode = $this->sys_token_decrypted($user_token);
        //查询
        $where['token']    = $token_decode;
        $where['act_type'] =  $act_type;
        $res = Db::name("user_token")->where($where)->find();
        //验证结果是否存在
        if(empty($res)){
            $data=array('status'=>'2','message'=>'您的账户在其他设备登录，您已下线！');
        }else{
            //验证是否超时：目前设置token有效时间为12个月
            $oldtime = date('Y-m-d H:i:s',$res['last_time']);
            $check_time = strtotime(date("Y-m-d H:i:s",strtotime("$oldtime   +12  month")));
            if($check_time  <  time()){
                $data=array('status'=>'2','message'=>'token已过期，请重新登录');
            }else if($user_id != $res['user_id']){
                $data=array('status'=>'2','message'=>'token令牌验证失败');
            }else{
                $data=array('status'=>'1','message'=>'验证通过');
            }
        }
        return  $data;
    }


    /**
     * @param 字符串加密 用于token值
     * @param
     * @return 加密后的字符串
     */
    function sys_token_encryption($string = '') {
        $skey="codeforphp666";
        $strArr = str_split(base64_encode($string));
        $strCount = count($strArr);
        foreach (str_split($skey) as $key => $value)
            $key < $strCount && $strArr[$key].=$value;
        return str_replace(array('=', '+', '/'), array('O0O0O', 'o000o', 'oo00o'), join('', $strArr));
    }


    /**
     * @param 字符串解密 用于token值
     * @param
     * @return 解密后的字符串
     */
    function sys_token_decrypted($string = '') {
        $skey="codeforphp666";
        $strArr = str_split(str_replace(array('O0O0O', 'o000o', 'oo00o'), array('=', '+', '/'), $string), 2);
        $strCount = count($strArr);
        foreach (str_split($skey) as $key => $value)
            $key <= $strCount  && isset($strArr[$key]) && $strArr[$key][1] === $value && $strArr[$key] = $strArr[$key][0];
        return base64_decode(join('', $strArr));
    }


}